<?php
/**
 * 文章管理
 * Created by PhpStorm.
 * User: andy
 * Date: 2019/8/29
 * Time: 下午6:42
 */

namespace app\common\model;

use think\Model;

class ArticleModel extends Model
{
    const SHOW_STATUS = 1; //显示
    const HIDE_STATUS = 0; //不显示

    protected $autoWriteTimestamp = true;

    protected $pk = 'article_id';

    public function cat()
    {
        return $this->hasOne('ArticleCategoryModel', 'cat_id', 'cat_id')->field('cat_id,cat_key,cat_name');
    }

    /**
     * 所有文章
     * @param int $pageSum 每页显示条数
     * @param bool $status 是否需要分页
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getALL($where = [], $pageSum = 0)
    {
        if ($pageSum <= 0) {
            $pageSum = getSystem("pageSUM") ? getSystem("pageSUM") : 10;
        }

        $list = self::where('article_id', '>', 0)
            ->with('cat')
            ->where($where)
            ->order('hot desc,create_time desc')
            ->paginate($pageSum);

        return $list;
    }

    /**
     * 获取已发布文章列表
     * @param $catName
     * @param int $pageSum
     * @return \think\Paginator
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getList($catName, $pageSum = 0,$where=[])
    {
        if ($pageSum <= 0) {
            $pageSum = getSystem("pageSUM") ? getSystem("pageSUM") : 10;
        }

        $t=true;
        if (!empty($catName)) {
            $cat = ArticleCategoryModel::field("cat_id,cat_name")
                ->where('status', ArticleCategoryModel::SHOW_STATUS)
                ->where('cat_key', $catName)
                ->find();

            if (empty($cat)) {
                return ['status' => 0];
            }
        } else {
            $t=false;
        }


        $model = self::where('status', self::SHOW_STATUS)
            ->with('cat')
            ->where('publish_time', '<=', time());

        if($t) $model->where('cat_id', $cat->cat_id);

        if(isset($where['title']) && !empty($where['title'])) $model->where('title','like',"%{$where['title']}%");

        $list = $model->order('hot desc,create_time desc')
            ->paginate($pageSum);

        if($t) $data["cat_name"] = $cat->cat_name;

        foreach ($list as $item){
            $item["collectCount"] = ArticleCollectModel::where('article_id', $item["article_id"])
                ->where("status", ArticleCollectModel::SHOW_STATUS)
                ->count();

            $item["msgCount"] = ArticleMessageModel::where('article_id', $item["article_id"])
                ->where("status", ArticleMessageModel::SHOW_STATUS)
                ->count();
        }

        $data["list"] = $list;

        return $data;
    }

    /**
     * 获取文章详情
     * @param $id
     * @return array|null|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getDetails($id)
    {
        $field = "title,article_id,content,author,publish_time,keywords,click,cat_id";
        $info = self::field($field)
            ->with("cat")
            ->where('status', self::SHOW_STATUS)
            ->where('article_id', $id)
            ->where('publish_time', '<=', time())
            ->find();

        if (!empty($info)) {
            //点击次数
            $info->click = $info->click + 1;
            $info->save();
        }

        return $info;
    }


    /**
     * 增加
     * @param $data
     * @return array
     * @throws \think\exception\DbException
     */
    public function adds($data)
    {

        if (empty($data['article_id'])) {
            $data["publish_time"] = strtotime($data["publish_time"]);
            $status = self::save($data);

            if ($status) {
                return ['status' => 1, 'msg' => '增加成功！'];
            } else {
                return ['status' => 0, 'msg' => '增加失败！'];
            }
        } else {
            $data["publish_time"] = strtotime($data["publish_time"]);
            $status = self::save($data, ['article_id' => $data["article_id"]]);

            if ($status) {
                return ['status' => 1, 'msg' => '修改成功！'];
            } else {
                return ['status' => 0, 'msg' => '修改失败！'];
            }
        }

    }

    /**
     * 删除
     * @param $id
     * @return array
     * @throws \think\exception\DbException
     */
    public function del($id)
    {

        $status = self::destroy($id);

        ArticleMessageModel::where('article_id',$id)->delete();
        ArticleCollectModel::where('article_id',$id)->delete();

        if ($status) {
            self::getALL(1);
            return ['status' => 1, 'msg' => '删除成功！'];
        } else {
            return ['status' => 0, 'msg' => '删除失败！'];
        }

    }

    /**
     * 根据分类标识查询指定列表
     * @param $key 关键标识
     * @param int $limit 查询条数，默认5条
     * @param bool $hot 是否只查推荐文章
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getKeyArticle($key, $limit = 5, $hot = false)
    {
        $cat = ArticleCategoryModel::field("cat_id,cat_key,cat_name")
            ->where('cat_key', $key)
            ->where('status', ArticleCategoryModel::SHOW_STATUS)
            ->find();

        if(empty($cat)){
            return [];
        }

        $query = self::field("article_id,cat_id,title,create_time,link,thumb,hot,publish_time")
            ->where('status', self::SHOW_STATUS)
            ->where('cat_id', $cat->cat_id)
            ->where('publish_time', '<=', time());

        if ($hot) {
            $query->where('hot', 1);
        }

        $list = $query->limit($limit)->select();

        return $list;
    }

}